﻿using System.Collections.Generic;
using System.Linq;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

namespace TfsMerge.Utils
{
    static class DxHelper
    {
        public static T GetFocusedRowAs<T>(GridControl grid)
            where T : class
        {
            if (grid == null)
                return null;

            return GetFocusedRowAs<T>(grid.FocusedView as GridView);
        }

        public static T GetFocusedRowAs<T>(GridView gridView) 
            where T : class
        {
            if (gridView == null)
                return null;

            return gridView.GetRow(gridView.FocusedRowHandle) as T;
        }

        public static bool IsRowDoubleClick(GridControl grid)
        {
            var view = grid.FocusedView as GridView;
            if (view == null)
                return false;

            var hi = view.CalcHitInfo(grid.PointToClient(Cursor.Position));
            if (hi.HitTest != GridHitTest.RowCell &&
                hi.HitTest != GridHitTest.RowIndicator)
                return false;

            return true;
        }

        public static IEnumerable<T> GetSelectedRowsAs<T>(GridView gridView)
            where T : class
        {
            return gridView.GetSelectedRows()
                .Select(gridView.GetRow).OfType<T>();
        }
    }
}
